package pl.donajski.magisterka;

import java.util.List;

public class GreedyGenerator implements IInitialStateGenerator {

	public State getInitialState(List<Task> tasks, List<Node> nodes) {
		State s = new State(tasks, nodes);

		for(Task t : tasks) {
			t.setAssignment(nodes.get(0));
		}
		
		s.setFlows();
		s.calculateCost();
		
		
		for(Task t : tasks) {
			IMove bestMove   = null;
			int   bestCost   = Integer.MAX_VALUE,
				  currCost   = Integer.MAX_VALUE;
			for(Node n : nodes) {
				//processing max constraint
				if(t.getAssignment().equals(n) || !n.canAssign())
					continue;
				
				//primary and backup task not on the same node constraint
				if(t.getPrimaryIndex() != null && t.getPrimaryIndex().getAssignment().equals(n))
					continue;
				
				IMove m = new Substitution(t, n, 1, 1);
				currCost = s.getCostAfterMove(m);
				
				if(bestCost > currCost || ( !t.getAssignment().isValid() && bestMove == null )) {
					bestMove = m;
					bestCost = currCost;
				}
			}
			if(bestMove != null)
				s.move(bestMove);
		}
		
		for(Task t : tasks) {
			IMove bestMove   = null;
			int   bestCost   = Integer.MAX_VALUE,
				  currCost   = Integer.MAX_VALUE;
			for(Node n : nodes) {
				//processing max constraint
				if(t.getAssignment().equals(n) || !n.canAssign() || (!t.isPrimary() && t.getPrimaryIndex().getAssignment().equals(n)))
					continue;
				
				//primary and backup task not on the same node constraint
				if(t.getPrimaryIndex() != null && t.getPrimaryIndex().getAssignment().equals(n))
					continue;
				
				IMove m = new Substitution(t, n, 1, 1);
				currCost = s.getCostAfterMove(m);
				
				if(bestCost > currCost || ( !t.getAssignment().isValid() && bestMove == null )) {
					bestMove = m;
					bestCost = currCost;
				}
			}
			if(bestMove != null)
				s.move(bestMove);
		}
		
		if(!s.isValid())
			throw new RuntimeException("INVALID STATE");
		
		
		return s;
	}
}
